package spring.mvc.hibernate;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import javax.transaction.Transactional;

import models.DepartmentDAO;
import models.EmployeeDAO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import entities.Employee;


/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
	
	@Autowired
	private EmployeeDAO epDAO;
	
	@Autowired
	private DepartmentDAO dpDAO;
	
	@Transactional
	@RequestMapping(value = "/")
	public ModelAndView home() {
		ModelAndView model = new ModelAndView("home");
		model.addObject("EmployeeList", epDAO.listEmployee());
		model.addObject("DepartmentList", dpDAO.listDepartment());
		return model;
	}
	
	@InitBinder
	public void initBinder(WebDataBinder binder) {
	    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	    sdf.setLenient(true);
	    binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
	}
	
	@Transactional
	@RequestMapping(value="saveEmployee" , method = RequestMethod.POST)
	public ModelAndView saveEmployee(@ModelAttribute Employee employee){
		epDAO.saveOrUpdate(employee);
		return new ModelAndView("home");
	}
	
	@Transactional
	@RequestMapping(value="newEmployee", method = RequestMethod.GET)
	public ModelAndView openNewEmployee(){
		ModelAndView model = new ModelAndView("newemployee");
		model.addObject("employee", new Employee());
		return model;
	}
	
	
	
}
